<?php

namespace App\Http\Controllers;

use App\Http\Resources\TokenResource;
use App\Http\Resources\UserResource;
use App\Parents;
use App\Student;
use App\Teacher;
use App\Traits\Api;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class UserController extends Controller
{
    use AuthenticatesUsers, Api;

    /**
     * 登陆接口
     *
     * @param Request $request
     * @return TokenResource
     * @throws \Exception
     */
    public function login(Request $request)
    {
        $userName = $request->input('name');
        $userPassword = $request->input('password');
        $user = User::where('name', $userName)->first()->toArray();

        // 请求接口得到 用户授权信息
        $authResult = $this->auth($userName, $userPassword);

        //dd($authResult);die;
        // 这里不是很清楚这个接口到底怎么返回值的，假设是这样。
        if ($authResult['status'] != 200) {
            throw new \Exception($authResult['msg'], $authResult['data']['status']);
        }

        // 这里简单写，不知道业务具体是怎样，暂不抽象service层
        $data = [];
        if (isset($authResult['data']['teacher'])) {
            // 查询teacher
            $data['teacher'] = Teacher::where('teacher_id', $authResult['data']['teacher']['user_id'])->first();
            $data['token'] = $authResult['data']['teacher']['token'];
        }
        if (isset($authResult['data']['student'])) {
            // 查询student
            $data['student'] = Student::where('student_id', $authResult['data']['student']['user_id'])->first();
            $data['token'] = $authResult['data']['student']['token'];
        }
        if (isset($authResult['data']['parents'])) {
            // 查询parent
            $data['parents'] = Parents::where('parents_id', $authResult['data']['parents']['user_id'])->first();
            $data['token'] = $authResult['data']['parents']['token'];
        }

        // 登陆
        if ($this->guard()->loginUsingId($user['id'], false)) {
            $request->session()->regenerate();
        }

        // 更新token
        $request->user()->forceFill([
            'api_token' => hash('sha256', $data['token']),
        ])->save();

        return new TokenResource($data);
    }

    /**
     * 获取当前用户信息
     *
     * @param Request $request
     * @return UserResource
     */
    public function user(Request $request)
    {
        return new UserResource($request->user());
    }

}
